import G6 from '@antv/g6';
import iconfontModel from '@/assets/iconfont/iconfont.json';

const { glyphs, font_family, css_prefix_text } = iconfontModel;

export const getIcons = (icon = 'icon-default') => {
    let icons = {};
    glyphs.map((item) => (icons[`${css_prefix_text}${item.font_class}`] = item.unicode));
    return unescape('%u' + icons[icon]);
};

export const nodeMouseFn = (evt, flag, graph) => {
    const node = evt.item;
    const model = node.getModel();
    const edges = node.getEdges();
    if (!model.closeActive) {
        graph.setItemState(node, 'active', flag);
    }
    edges.forEach((edge) => graph.setItemState(edge, 'running', flag));
};

export const nodeColors = [
    '#3056E3',
    '#EF9F1F',
    '#BD10E0',
    '#008000',
    '#F6C3B7',
    '#B6E3F5',
    '#D3C6EA',
    '#FFD8B8',
    '#AAD8D8',
    '#FFD6E7',
];

/**
 * 生成唯一字符串
 */
export const uuid = () => {
    const s = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i += 1) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4';
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = '-';
    s[13] = '-';
    s[18] = '-';
    s[23] = '-';
    return s.join('');
};

// 文本超出隐藏 (字段, 最大长度, 字体大小)
export const fittingString = (str, maxWidth, fontSize = 14) => {
    const ellipsis = '...';
    const ellipsisLength = G6.Util.getTextSize(ellipsis, fontSize)[0];
    let currentWidth = 0;
    let res = str;
    const pattern = new RegExp('[\u4E00-\u9FA5]+'); // 区分汉字和字母
    str?.split('')?.forEach((letter, i) => {
        if (currentWidth > maxWidth - ellipsisLength) return;
        if (pattern.test(letter)) {
            // 中文字符
            currentWidth += fontSize;
        } else {
            // 根据字体大小获取单个字母的宽度
            currentWidth += G6.Util.getLetterWidth(letter, fontSize);
        }
        if (currentWidth > maxWidth - ellipsisLength) {
            res = `${str.substr(0, i)}${ellipsis}`;
        }
    });
    return res;
};
